package br.com.fatecpg.songs.util;


import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FacesContextUtil implements java.io.Serializable {          

    private FacesContextUtil() {
    }
                
    public static void putOnSessionMap(String key, Object value) {        
        sessionMap().put(key, value);        
    }
    
    public static Object getFromSessionMap(String key) {        
        return sessionMap().get(key);        
    }

    public static Object removeFromSessionMap(String key) {        
        return sessionMap().remove(key);        
    }
    
    public static void handleNavigation(String outcome) {
        context().getApplication().getNavigationHandler().handleNavigation(context(), null, outcome);
    }   

    public static FacesContext context() {
        return FacesContext.getCurrentInstance();
    }

    private static Map<String, Object> sessionMap() {        
        return externalContext().getSessionMap();
    }

    public static HttpSession getSession(boolean create) {
        return (HttpSession) externalContext().getSession(create);
    }

    public static HttpServletRequest request() {
        return (HttpServletRequest) externalContext().getRequest();
    }

    public static HttpServletResponse response() {
        return (HttpServletResponse) externalContext().getResponse();
    }

    public static String getNavigationUrl() {        
        return context().getViewRoot().getViewId();
    } 
    
    public static String getParameter(String key){
        return externalContext().getRequestParameterMap().get(key);
    }
    
    public static void redirect(String url) throws Exception{
        externalContext().redirect(url);
    }
    
    public static void refresh() {
        try{
            redirect(request().getRequestURI());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    private static ExternalContext externalContext(){
        return context().getExternalContext();
    }
            
    public static void addMessage(String message) {        
        context().addMessage(null, new FacesMessage(message));
    }
}
